package com.ry.request;

import com.ry.common.utils.RedisUtil;
import com.ry.model.ProductInventory;
import com.ry.service.ProductInventoryService;
import lombok.extern.slf4j.Slf4j;

/**
 * 刷新redis缓存库存的请求
 *
 * 如果请求过来没有在缓存中查询到库存，那么存在两种情况：
 *  1、还没有人请求过这个库存数据，缓存未初始化
 *  2、已经有人请求过这个库存数据，被LRU算法清除掉了
 */
@Slf4j
public class InventoryRefreshCacheRequest implements InventoryRequest {

    /**
     * redis缓存工具类
     */
    private RedisUtil redisUtil;

    /**
     * 商品库存service
     */
    private ProductInventoryService productInventoryService;

    /**
     * 商品库存实体
     */
    private Long productId;

    /**
     * 是否强制刷新缓存
     */
    private boolean isForced = false;

    @Override
    public void process() {

        // 1、查询数据库中最新的库存数据
        ProductInventory productInventory = productInventoryService.queryInventoryById(productId);

        log.info("===日志===：已查询到商品最新的库存数量，商品id={},商品库存={}",productId,productInventory.getInventoryCnt());

        // 2、更新库存数据至缓存
        redisUtil.putInventoryCache(productInventory);
    }

    public InventoryRefreshCacheRequest(RedisUtil redisUtil, ProductInventoryService productInventoryService, Long productId) {
        this.redisUtil = redisUtil;
        this.productInventoryService = productInventoryService;
        this.productId = productId;
    }

    public InventoryRefreshCacheRequest(RedisUtil redisUtil, ProductInventoryService productInventoryService, Long productId, boolean isForced) {
        this.redisUtil = redisUtil;
        this.productInventoryService = productInventoryService;
        this.productId = productId;
        this.isForced = isForced;
    }

    @Override
    public Long getProductId() {
        return productId;
    }

    @Override
    public boolean isForced() {
        return isForced;
    }
}
